<?php

namespace Hilaoyu\LaravelExtend\Services\Auth\Controllers;

use Hilaoyu\LaravelExtend\ControllerBase;
use Hilaoyu\LaravelExtend\Services\Auth\AuthService;
use Hilaoyu\LaravelExtend\Services\Captcha\CaptchaService;
use Hilaoyu\Utils\UtilSupport;
use Illuminate\Auth\GenericUser;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Str;

class ResetPasswordController extends ControllerBase
{


    protected function showResetForm(Request $request)
    {
        comResponse()->with(AuthService::GuardKey(), 'guard');
        return $this->renderingResponse();
    }
    public function send(Request $request){
        $account = request()->input('account', '');
        $send_type = request()->input('send_type', '');
        $code_id = request()->input('code_img_id', '');
        $code_val = request()->input('code_img_val', '');
        $E_captcha = new CaptchaService();

        $guard_key = AuthService::GuardKey();

        if (!$E_captcha->verify($code_id, $code_val,null,true)) {
            comResponse()->failed('发送失败')->withErrors(['code_img_val' => '验证码错误']);
            return $this->renderingResponse();
        }


        if(
            !in_array($send_type,['mobile','email'])
            || ('mobile' == $send_type && !AuthService::GetGuardProviderConfig($guard_key,'allow_mobile_reset_pass'))
            || ('email' == $send_type && !AuthService::GetGuardProviderConfig($guard_key,'allow_email_reset_pass'))
        ){
            comResponse()->failed('发送失败')->withErrors(['send_type' => '不支持的发送方式']);
            return $this->renderingResponse();
        }

        $credentials = [
            'account' =>$account
        ];
        if('mobile' == $send_type){
            $credentials = [
                'mobile' =>$account
            ];
        }elseif ('email' == $send_type){
            $credentials = [
                'email' =>$account
            ];
        }
        //如果作为客户端使用，先在用户中心注册
        if($client = AuthService::ProviderUseAsClient()){
            $user = $client->userGet($credentials);

        }else{
            $user = AuthService::LoadUser($credentials,$guard_key);
        }

        if(! $user ){
            comResponse()->failed('账号不存在，发送验证码失败')->withErrors(['account' => '账号不存在']);
            return $this->renderingResponse();
        }

        $captcha_code_id = '';
        $send_to = '';
        switch ($send_type){
            case "mobile":
                if(! ($mobile = data_get($user,'mobile',''))){
                    comResponse()->withErrors(['account' => '此账号没有绑定手机号']);
                    break;
                }
                $captcha_code_id = $E_captcha->generateMobile($mobile,'captcha_reset_password');
                $send_to = substr_replace($mobile,'****',3,4);
                break;
            case "email":
                if(! ($email = data_get($user,'email',''))){
                    comResponse()->withErrors(['account' => '此账号没有绑定邮箱']);
                    break;
                }
                $captcha_code_id = $E_captcha->generateEmail($email,'captcha_reset_password');
                $send_to = substr_replace(Str::beforeLast($email,'@'),'****',3) . '@'.Str::afterLast($email,'@');
                break;
            default:
                break;
        }

        if(!$captcha_code_id){
            comResponse()->failed('发送失败')->withErrors($E_captcha->getError());
            return $this->renderingResponse();
        }

        //如果作为客户端使用，先在用户中心注册
        $user_id = data_get($user,'id');
        $update_data = [
            'reset_password_code_id' => $captcha_code_id,
        ];
        if($client = AuthService::ProviderUseAsClient()){
            $user = $client->userUpdate(['id'=>$user_id],$update_data);
            if(!$user){
                if($message = $client->getResult('message')){
                    comResponse()->withErrors($message);
                }

                comResponse()->withErrors($client->getError());
            }
        }else{
            $user = AuthService::SaveUser($update_data,$user_id,$guard_key,false);
            if(!$user){
                comResponse()->withErrors(AuthService::GetStaticError());
            }
        }


        if($user){
            comResponse()->success('验证码已发到 '. $send_to)->with([
                'account'=>data_get($user,'account',''),
                'id'=>data_get($user,'id',''),
            ]);
        }else{
            comResponse()->failed('服务器出错，请稍后重试');
        }



        return $this->renderingResponse();

    }
    public function reset(){
        $send_type = request()->input('send_type', '');
        $user_id = request()->input('user_id', '');
        $code_val = request()->input('code_val', '');


        $guard_key = AuthService::GuardKey();
        if(
            !in_array($send_type,['mobile','email'])
            || ('mobile' == $send_type && !AuthService::GetGuardProviderConfig($guard_key,'allow_mobile_reset_pass'))
            || ('email' == $send_type && !AuthService::GetGuardProviderConfig($guard_key,'allow_email_reset_pass'))
        ){
            comResponse()->failed('重置失败')->withErrors(['send_type' => '不支持重置方式']);
            return $this->renderingResponse();
        }
        $credentials = [
            'id' =>$user_id
        ];
        //如果作为客户端使用，先在用户中心注册
        if($client = AuthService::ProviderUseAsClient()){
            $user = $client->userGet($credentials);

        }else{
            $user = AuthService::LoadUser($credentials,$guard_key);
        }

        if(! $user ){
            comResponse()->failed('账号不存在，重置失败')->withErrors(['account' => '账号不存在']);
            return $this->renderingResponse();
        }

        $pass = request()->input('password', '');
        $pass_confirm = request()->input('password_confirm', '');

        if($pass != $pass_confirm){
            comResponse()->failed('两次输入的密码不一致')->withErrors(['password_confirm' => '两次输入的密码不一致']);
            return $this->renderingResponse();
        }

        if(true !== ($check = AuthService::CheckPasswordHandle($pass,$user))){
            return comResponse()->failed((string)$check)->json();
        }

        $send_to = '';
        switch ($send_type){
            case "mobile":
                $send_to = data_get($user,'mobile','');
                break;
            case "email":
                $send_to = data_get($user,'email','');
                break;
            default:
                break;
        }

        $code_id = data_get($user,'reset_password_code_id','');

        $E_captcha = new CaptchaService();
        if (!$E_captcha->verify($code_id, $code_val,$send_to)) {
            comResponse()->failed('验证出错')->withErrors(['code_val' => '验证码错误']);
            return $this->renderingResponse();
        }

        //如果作为客户端使用，先在用户中心注册
        $update_data = [
            'reset_password_code_id' => '',
            'password' => $pass,
        ];
        if($client = AuthService::ProviderUseAsClient()){
            $user = $client->userUpdate(['id'=>$user_id],$update_data);
            if(!$user){
                comResponse()->failed($client->getResult('message'))->withErrors($client->getError());
            }
        }else{
            $update_data['password'] = AuthService::PasswordEn($pass,$guard_key);
            $user = AuthService::SaveUser($update_data,$user_id,$guard_key,false);
            if(!$user){
                comResponse()->withErrors(AuthService::GetStaticError());
            }
        }

        if($user){
            comResponse()->success('重置成功');
        }else{
            comResponse()->failed('服务器出错，请稍后重试');
        }


        return $this->renderingResponse();

    }
}
